package com.scs.application.modules.print.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.print.dto.TemplateDTO;
import com.scs.application.modules.print.entity.Field;
import com.scs.application.modules.print.entity.Template;
import com.scs.application.modules.print.mapper.FieldMapper;
import com.scs.application.modules.print.mapper.TemplateMapper;
import com.scs.application.modules.print.service.TemplateService;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 打印模板实现类
 */
@Service
public class TemplateServiceImpl extends BaseServiceImpl<TemplateMapper, Template> implements TemplateService {

    @Autowired
    private FieldMapper fieldMapper;

    @Override
    public boolean saveOrUpdate(Template entity) {
        Template template = super.getOne(new QueryWrapper<Template>()
                .eq("bus_type", entity.getBusType())
                .eq("print_type", entity.getPrintType())
                .ne(StringUtils.isNotEmpty(entity.getId()), "id", entity.getId()).last("LIMIT 1"));
        if(template != null) {
            throw new BusinessException("已添加该模板，无需重复添加");
        }
        return super.saveOrUpdate(entity);
    }

    @Override
    public Boolean isSupport(Boolean flagProject) {
        return flagProject;
    }

    /**
     * 根据bustype获取实体
     * @param busType
     * @return
     */
    public TemplateDTO getTemplateDTO(String busType) {
        Template template = this.getOne(Wrappers.<Template>query().eq("bus_type", busType).last("limit 1"));
        if (template == null) {
            return null;
        }
        List<Field> fields = fieldMapper.selectList(Wrappers.<Field>query().eq("template_id", template.getId()));

        TemplateDTO templateDTO = new TemplateDTO();
        BeanUtils.copyProperties(template, templateDTO);

        if (fields != null && !fields.isEmpty()) {
            templateDTO.setFieldDTOS(Lists.newArrayListWithCapacity(fields.size()));
            for(Field field : fields) {
                TemplateDTO.FieldDTO fieldDTO = new TemplateDTO.FieldDTO();
                BeanUtils.copyProperties(field, fieldDTO);
                templateDTO.getFieldDTOS().add(fieldDTO);
            }
        }
        return templateDTO;
    }

    public TemplateDTO getDTOById(String templateId) {
        return null;
    }

    public List<TemplateDTO> getDTOList() {
        return null;
    }
}
